package com.tl.web02.controller.ajax_version;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tl.web02.config.Config;
import com.tl.web02.constant.ResponseResult;
import com.tl.web02.service.LoginAndRegisterService;
import com.tl.web02.utils.JsonParamUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;

/**
 *
 */
@WebServlet(name = "AjaxLoginServlet", urlPatterns = "/ajax_login")
public class AjaxLoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取参数
        //获取参数
        JSONObject jsonParam = JsonParamUtil.getJsonParam(req);
        String username = jsonParam.getString("username");
        String password = jsonParam.getString("password");
        //配置响应编码
        req.setCharacterEncoding(Config.REQ_ChARSET);
        resp.setContentType(Config.RESP_JSON_CONTENT_TYPE);
        //获取输出
        PrintWriter out = resp.getWriter();
        //获取map
        ServletContext application = req.getServletContext();
        HashMap<String, String> userMap = (HashMap<String, String>) application.getAttribute(Config.USER_MAP);
        //登录的方法
        ResponseResult result = LoginAndRegisterService.login(userMap, username, password);
        //向页面输出该结果
        out.print(JSONObject.toJSONString(result));
    }
}
